﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"Sequence-list.h"

void SLInit(SL* ps) {//传地址
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

void SLDestroy(SL* ps) {
	if (ps->arr) {
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

//把插入判断单独封装
void SLCheckCapacity(SL* ps) {
	//插入数据之前先看空间够不够
	if (ps->capacity == ps->size) {
		//申请空间
		//malloc calloc realloc用哪个  
		//判断capacity是否为0
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
		if (NULL == tmp) {
			perror("realloc fail!");
			exit(1);//直接退出程序
		}
		//空间申请成功
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}

//尾插
void SLPushBack(SL* ps, SLDataType x) {
	
	assert(ps);
	SLCheckCapacity(ps);
	//ps->arr[ps->size] = x;
	//++ps->size;
	ps -> arr[ps->size++] = x;
}


//头插
void SLPushFront(SL* ps, SLDataType x) {
	assert(ps);
	SLCheckCapacity(ps);
	//先让顺序表的数据整体往后移动一位
	for (int i = ps->size; i > 0; i--) {
		ps->arr[i] = ps->arr[i-1];	
	}
	ps->arr[0] = x;
	ps->size++;
}

//尾删
void SLPopBack(SL* ps) {
	assert(ps);
	assert(ps->size);
	//顺序表不为空
	//ps->arr[ps->size-1] = -1;
	--ps->size;
}

//头删
void SLPopFront(SL* ps) {
	assert(ps);
	assert(ps->size);
	
	//数据整体往前挪动一位
	for (int i = 0; i < ps->size - 1;i++) {   //少了一个，总数是size-1，所以是0->[size-2]总共size-1个
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}



//指定位置之前插⼊/删除数据     1 2 3   pos=1,
void SLInsert(SL* ps, int pos, SLDataType x) {
	assert(ps);
	assert(pos>=0 && pos<=ps->size);
	//插入数据：空间够不够
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos;i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}
void SLErase(SL* ps, int pos) {
	assert(ps);
	assert(ps->arr);
	assert(pos >= 0 && pos < ps->size);
	//
	for (int i = pos; i < ps->size - 1;i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}


////查找指定位置的数据
//int SLFind(SL* ps, SLDataType x) {
//	assert(ps);
//	for (int i = 0; i < ps->size; i++)
//	{
//		if (ps->arr[i]==x) {
//			return i;
//		}
//	}
//	//没有找到
//	return -1;//无效的下标整数就行
//}







//void SLPrint(SL s) {
//	for (int i = 0; i < s.size; i++) {
//		printf("%d ", s.arr[i]);
//	}
//	printf("\n");
//}